package com.ldk.base.framework.common;

import java.io.Serializable;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

public class CustomPageable implements Pageable, Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 9193202464613378155L;
	private int offset;
	private int size;
	private int pageNumber;
	private Sort sort;
	
	public CustomPageable(){
		this(0, 0, null);
	}
	
	public CustomPageable(int offset, int size)
	{
		this(offset, size, null);
	}
	
    public CustomPageable(int offset, int size, Sort sort){
    	this.offset = offset < 0 ? 0 : offset;
		this.size = size;
		
		this.pageNumber = (int)(this.offset / this.size);
		
		this.sort = sort;
    }
	
	@Override
	public int getPageNumber() {
		return this.pageNumber;
	}

	@Override
	public int getPageSize() {
		return this.size;
	}

	@Override
	public int getOffset() {
		return this.offset;
	}

	@Override
	public Sort getSort() {
		return this.sort;
	}
	
	@Override
	public Pageable next() {
		int nextOffset = getOffset() + getPageSize();
		return new CustomPageable(nextOffset, getPageSize(), getSort());
	}

	@Override
	public Pageable previousOrFirst() {
		int preOffset = getOffset() - getPageSize();
		if(preOffset < 0)
			preOffset = 0;
		return new CustomPageable(preOffset, getPageSize(), getSort());
	}

	@Override
	public Pageable first() {
		return new CustomPageable(0, getPageSize(), getSort());
	}

	@Override
	public boolean hasPrevious() {
		int preOffset = getOffset() - getPageSize();
		return preOffset > 0;
	}

}
